package com.sso.risk.controller;

import com.sso.common.dto.ApiResponse;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 风控系统主控制器
 * 
 * @author SSO System
 * @since 2024-01-01
 */
@Controller
public class RiskController {

    private final Random random = new Random();

    /**
     * 首页（登录后）
     */
    @GetMapping("/")
    public String home(@AuthenticationPrincipal OidcUser principal, Model model) {
        if (principal != null) {
            model.addAttribute("username", principal.getPreferredUsername());
            model.addAttribute("fullName", principal.getFullName());
            model.addAttribute("email", principal.getEmail());
            return "home";
        }
        return "index"; // 未登录用户显示欢迎页面
    }

    /**
     * 欢迎页面（登录前）
     */
    @GetMapping("/welcome")
    public String welcome() {
        return "index";
    }

    /**
     * 登录页面
     */
    @GetMapping("/login")
    public String login() {
        return "login";
    }

    /**
     * 仪表板
     */
    @GetMapping("/dashboard")
    public String dashboard(@AuthenticationPrincipal OidcUser principal, Model model) {
        if (principal != null) {
            model.addAttribute("username", principal.getPreferredUsername());
            model.addAttribute("fullName", principal.getFullName());
            model.addAttribute("email", principal.getEmail());
            model.addAttribute("authorities", principal.getAuthorities());
        }
        return "dashboard";
    }

    /**
     * 风险监控页面
     */
    @GetMapping("/monitoring")
    @PreAuthorize("hasAuthority('SCOPE_read') or hasAuthority('risk:read')")
    public String monitoring(@AuthenticationPrincipal OidcUser principal, Model model) {
        model.addAttribute("username", principal.getPreferredUsername());
        return "monitoring";
    }

    /**
     * 风险评估页面
     */
    @GetMapping("/assessment")
    @PreAuthorize("hasAuthority('SCOPE_write') or hasAuthority('risk:write')")
    public String assessment(@AuthenticationPrincipal OidcUser principal, Model model) {
        model.addAttribute("username", principal.getPreferredUsername());
        return "assessment";
    }

    /**
     * 风险管理页面
     */
    @GetMapping("/management")
    @PreAuthorize("hasAuthority('SCOPE_risk:manage') or hasAuthority('risk:manage')")
    public String management(@AuthenticationPrincipal OidcUser principal, Model model) {
        model.addAttribute("username", principal.getPreferredUsername());
        return "management";
    }

    /**
     * API: 获取风险警报列表
     */
    @GetMapping("/api/alerts")
    @PreAuthorize("hasAuthority('SCOPE_read') or hasAuthority('risk:read')")
    @Cacheable(value = "risk-alerts", key = "#principal.preferredUsername")
    @ResponseBody
    public ApiResponse<Map<String, Object>> getAlerts(@AuthenticationPrincipal OidcUser principal) {
        Map<String, Object> data = new HashMap<>();
        data.put("alerts", java.util.List.of(
                Map.of("id", 1, "type", "异常交易", "level", "高", "description", "检测到大额异常转账", 
                       "amount", new BigDecimal("50000.00"), "createTime", LocalDateTime.now().minusMinutes(10)),
                Map.of("id", 2, "type", "登录异常", "level", "中", "description", "异地登录检测", 
                       "location", "北京", "createTime", LocalDateTime.now().minusMinutes(30)),
                Map.of("id", 3, "type", "频繁操作", "level", "低", "description", "短时间内频繁操作", 
                       "count", 15, "createTime", LocalDateTime.now().minusHours(1))
        ));
        data.put("total", 3);
        data.put("currentUser", principal.getPreferredUsername());
        
        return ApiResponse.success("获取风险警报成功", data);
    }

    /**
     * API: 获取风险统计数据
     */
    @GetMapping("/api/statistics")
    @PreAuthorize("hasAuthority('SCOPE_read') or hasAuthority('risk:read')")
    @Cacheable(value = "risk-statistics", key = "#principal.preferredUsername + '_' + T(java.time.LocalDate).now().toString()")
    @ResponseBody
    public ApiResponse<Map<String, Object>> getStatistics(@AuthenticationPrincipal OidcUser principal) {
        Map<String, Object> data = new HashMap<>();
        
        // 模拟统计数据
        data.put("todayAlerts", random.nextInt(20) + 5);
        data.put("highRiskCount", random.nextInt(5) + 1);
        data.put("mediumRiskCount", random.nextInt(10) + 3);
        data.put("lowRiskCount", random.nextInt(15) + 5);
        data.put("totalProcessed", random.nextInt(1000) + 500);
        data.put("riskScore", random.nextDouble() * 100);
        data.put("currentUser", principal.getPreferredUsername());
        data.put("updateTime", LocalDateTime.now());
        
        return ApiResponse.success("获取风险统计数据成功", data);
    }

    /**
     * API: 风险评估
     */
    @GetMapping("/api/assess")
    @PreAuthorize("hasAuthority('SCOPE_write') or hasAuthority('risk:write')")
    @ResponseBody
    public ApiResponse<Map<String, Object>> assessRisk(@AuthenticationPrincipal OidcUser principal) {
        Map<String, Object> result = new HashMap<>();
        
        // 模拟风险评估
        double riskScore = random.nextDouble() * 100;
        String riskLevel;
        if (riskScore > 80) {
            riskLevel = "高风险";
        } else if (riskScore > 50) {
            riskLevel = "中风险";
        } else {
            riskLevel = "低风险";
        }
        
        result.put("assessmentId", "RISK-" + System.currentTimeMillis());
        result.put("riskScore", riskScore);
        result.put("riskLevel", riskLevel);
        result.put("assessor", principal.getPreferredUsername());
        result.put("assessTime", LocalDateTime.now());
        result.put("recommendations", java.util.List.of(
                "加强交易监控",
                "提高验证级别",
                "增加人工审核环节"
        ));
        
        return ApiResponse.success("风险评估完成", result);
    }

    /**
     * API: 风险处理
     */
    @GetMapping("/api/handle")
    @PreAuthorize("hasAuthority('SCOPE_risk:manage') or hasAuthority('risk:manage')")
    @ResponseBody
    public ApiResponse<String> handleRisk(@AuthenticationPrincipal OidcUser principal) {
        // 模拟风险处理
        String handleId = "HANDLE-" + System.currentTimeMillis();
        return ApiResponse.success("风险处理任务已创建，任务ID: " + handleId);
    }

    /**
     * API: 用户信息
     */
    @GetMapping("/api/user/info")
    @ResponseBody
    public ApiResponse<Map<String, Object>> getUserInfo(@AuthenticationPrincipal OidcUser principal) {
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("username", principal.getPreferredUsername());
        userInfo.put("fullName", principal.getFullName());
        userInfo.put("email", principal.getEmail());
        userInfo.put("authorities", principal.getAuthorities());
        userInfo.put("claims", principal.getClaims());
        
        return ApiResponse.success("获取用户信息成功", userInfo);
    }
} 